//
//  CZEmoticonKeyboard.swift
//  表情键盘新工程-74.准备
//
//  Created by itcast on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

/// 表情键盘的view
class CZEmoticonKeyboard: UIView {
    
    // MARK: - 属性
    weak var textView: UITextView?

    private let cellReuseIdentifier = "cellReuseIdentifier"
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        // 指定frame
        let newFrame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 216)
        super.init(frame: newFrame)
        
        prepareUI()
    }
    
    private func prepareUI() {
        backgroundColor = UIColor.brownColor()
        
        // 1.添加到父控件
        self.addSubview(collectionView)
        self.addSubview(pageControl)
        self.addSubview(emotivonToolBar)
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        emotivonToolBar.translatesAutoresizingMaskIntoConstraints = false
        
        // 框架尽量少依赖其他框架,最好是用系统
        // 2.添加约束
        /* 
            VFL:
                1.H: 表示约束水平方向
                    1.|| 左边的表示父控件左边,右边的表示父控件右边
                2.V: 表示约束垂直方向
                    1.|| 左边的线表示父控件顶部, 右边的线表示父控件的底部
        */
        // collectionView的水平方向
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : self.collectionView]))
        
        // toolBar水平方向
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb" : self.emotivonToolBar]))
        
        // 垂直方向
        self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cv" : self.collectionView, "tb": self.emotivonToolBar]))
        
        // pageControl
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: collectionView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 25))
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 子控件的frame值就有了
        let itemSize = collectionView.frame.size
        // 设置collectionView的layout的大小
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = itemSize
    }
    
    // MARK: - 懒加载
    /// collectionView
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        
        // 水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        // 取消间距
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        // 创建collectionView
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        
        // 注册cell,使用自定义的cell
        cv.registerClass(CZEmoticonPageCell.self, forCellWithReuseIdentifier: self.cellReuseIdentifier)
        
        // 取消弹簧效果
        cv.bounces = false
        // 分页
        cv.pagingEnabled = true
        
        cv.backgroundView = UIImageView(image: UIImage(named: "emoticon_keyboard_background"))
        
        // 实现数据源
        cv.dataSource = self
        // 设置代理
        cv.delegate = self
        
        return cv
    }()
    
    /// pageControl
    private lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        
        // 设置
//        pageControl.numberOfPages = 5
//        pageControl.currentPage = 2
        
        pageControl.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        
        // _currentPageImage
        // 给谁设置值就用谁调用
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        // _pageImage
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        
//        UIPageControl.printIvars()
//        // 看不到其他的属成员变量,可以用运行时来获取私有的成员变量
//        // outCount: UnsafeMutablePointer<UInt32>
//        //  UnsafeMutablePointer<Ivar> // 数组中,数组名就是数组的首地址, 数组的首地址就是第一个元素的地址
//        var outCount: UInt32 = 0
//        let ivars = class_copyIvarList(UIPageControl.self, &outCount)
//        for var i:UInt32  = 0; i<outCount; i++ {
//            let ivar = ivars[Int(i)]
//            
//            let cName = ivar_getName(ivar)
//            
//            let name = String(CString: cName, encoding: NSUTF8StringEncoding)
//            print("name: \(name)")
//            
//            let cType = ivar_getTypeEncoding(ivar)
//            let type = String(CString: cType, encoding: NSUTF8StringEncoding)
//            print("type: \(type)")
//        }
        
        return pageControl
    }()
    
    /// toolBar
    private lazy var emotivonToolBar: CZEmoticonToolBar = {
        let toolBar = CZEmoticonToolBar()
        
        // 5.设置self成为toolBar的代理
        toolBar.delegate = self
        
        return toolBar
    }()
    
    // TODO: 测试,每组的cell数量
//    private var cellCounts = [1, 6, 4, 2]
}

// 6.遵守协议
extension CZEmoticonKeyboard: CZEmoticonToolBarDelegate {
    // 7.实现代理方法
    func didSelectButtonType(didSelectedType: CZEmoticonToolBarType) {
//        print("我在键盘view里面知道toolBar点击了: \(didSelectedType)")
//        print("切换到哪一组: \(didSelectedType.rawValue)")
        // collectionView切换到对应的组
        // 需要获取到点击的按钮是哪一组
        let indexPath = NSIndexPath(forItem: 0, inSection: didSelectedType.rawValue)
        collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.Left)
        
        // 设置pageControl
        setupPageControl(indexPath)
    }
}

// 扩展实现数据源协议
extension CZEmoticonKeyboard: UICollectionViewDataSource, UICollectionViewDelegate {
    // 返回多少组, 一组是一个表情包,看有多少个表情包
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return CZEmoticonManager.sharedManager.emoticonPackageModels.count
    }
    
    // 每组多少个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 获取对应这组的表情包模型
        let emoticonPackageModel = CZEmoticonManager.sharedManager.emoticonPackageModels[section]
        
        // 返回表情包里面表情的页数
        return emoticonPackageModel.pageEmotions.count
    }
    
    // 返回cell
    // 一页一个cell,一个cell里面有多个按钮
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as! CZEmoticonPageCell
        
//        cell.backgroundColor = UIColor.randomColor()
        cell.indexPath = indexPath
        
        /// 获取对应这组的表情包模型
        let emoticonPackageModel = CZEmoticonManager.sharedManager.emoticonPackageModels[indexPath.section]
        
        // 获取到cell对应这页的模型
        let pageEmoticon = emoticonPackageModel.pageEmotions[indexPath.item]
        cell.pageEmoticon = pageEmoticon
        
        // 设置代理
        cell.delegate = self
        
        return cell
    }
    
    // collectionView滚动会调用代理
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 判断哪个cell显示的多一点,就选中这个cell对应的组的按钮
        
        // 获取参照点,center是使用collectionView的左上角,cell的frame,的起始点是在collectionView的左上角还要在加上contentOffest.x
        var refPoint = collectionView.center
        refPoint.x += collectionView.contentOffset.x
//        print("refPoint: \(refPoint)")
        
        // 获取可以看得到的cell
        for cell in collectionView.visibleCells() {
            // 获取到每一个可见的cell
            
            // 看看哪个cell的frame包含参照点
            if cell.frame.contains(refPoint) {
                // 获取选中cell对应的indexPath.才知道要让toolBar选中哪个按钮
                let indexPath = collectionView.indexPathForCell(cell)
//                print("找到要显示哪组的cell了: \(indexPath)")
                
                // 切换toolBar的选中按钮
                emotivonToolBar.switchSelectedButtonWitchSection(indexPath!.section)
                
                // 设置pageControl
                setupPageControl(indexPath!)
//                let emoticonPackageModel = CZEmoticonManager.sharedManager.emoticonPackageModels[indexPath!.section]
//                pageControl.numberOfPages = emoticonPackageModel.pageEmotions.count
//                
//                pageControl.currentPage = indexPath!.item
            }
        }
    }
    
    private func setupPageControl(indexPath: NSIndexPath) {
        let emoticonPackageModel = CZEmoticonManager.sharedManager.emoticonPackageModels[indexPath.section]
        pageControl.numberOfPages = emoticonPackageModel.pageEmotions.count
        
        pageControl.currentPage = indexPath.item
        
        // 第0组不要显示
        pageControl.hidden = (indexPath.section == 0)
    }
}

extension CZEmoticonKeyboard: CZEmoticonPageCellDelegate {
    func emoticonPageCellDidClickDeleteButton() {
        // 删除
        textView?.deleteBackward()
    }
    
    func emoticonPageCellDidClickEmoticonButton(emoticonModel: CZEmoticonModel) {
//        print("CZEmoticonKeyboard: \(emoticonModel)")
        
        // 将模型对应的内容添加到textView上面
        textView?.insertEmoticon(emoticonModel)
        
        // 添加到最近
        CZEmoticonManager.sharedManager.addRecentEmoticon(emoticonModel)
    }
}